﻿using AspNetCore.Host.Routing;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace AspNetCore.Host.Hosting
{
    public class WebApplicationBuilder
    {
        public IWebHostEnvironment Environment { get; }
        public ConfigurationManager Configuration { get; }
        public IServiceCollection Services { get; }
        public ILoggingBuilder Logging { get; }

        public WebApplicationBuilder(
            IWebHostEnvironment environment,
            ConfigurationManager configuration)
        {
            Environment = environment;
            Configuration = configuration;
            Services = new ServiceCollection();
            Logging = new LoggingBuilder(Services);
        }

        public WebApplication Build()
        {
            Services.AddLogging();
            Logging.AddConsole();
            Logging.AddConfiguration(Configuration.GetSection("Logging"));
            Services.AddSingleton(Environment);
            Services.AddSingleton<IConfiguration>(Configuration);
            Services.AddSingleton<IFeatureCollection>(sp => 
            {
                var features = new FeatureCollection();
                features.Set(new EndpointDataSource());
                return features;
            });
            Services.Configure<KestrelOptions>(c => 
            {
                c.Url = "http://127.0.0.1:8080";
            });
            return new WebApplication(Services.BuildServiceProvider());
        }      
    }

    internal class LoggingBuilder : ILoggingBuilder
    {
        public IServiceCollection Services { get; }

        public LoggingBuilder(IServiceCollection services)
        {
            Services = services;
        }
    }
}
